<?php
require_once(dirname(__FILE__).'/JSMin.php');

class JSRequire {

	private $minify;

	public function __construct($minify = true) {
		$this->minify = $minify;
	}
	
	private function loadJSScript($script,$sourcePaths)
	{
		foreach($sourcePaths as $dir)
			if(file_exists($dir.$script.'.js'))
				return file_get_contents($dir.$script.'.js');
		throw new Exception('script not found in sourcePaths '.implode(',',$sourcePaths).' : '.$script);
	}

	private function handleClassRequires($content, $sourcePaths)
	{
		$requires = array();
		$pattern = "/Class.require\((.+)\);/";
		if(preg_match_all($pattern, $content, $matches))
		{
			foreach($matches[0] as $match)
			{
				$matchQuote = '"';
				if(strpos($match, "'") !== false)
					$matchQuote = "'"; 
				$matchValue = str_replace("Class.require(".$matchQuote, "", $match);
				$matchValue = str_replace($matchQuote.");", "", $matchValue);
				$requires []= $matchValue;
				$content = str_replace($match, "", $content);
			}
		}
	
		foreach($requires as $script)
		{
			$script = implode("/",explode(".",$script));
			$requiredContent = $this->loadJSScript($script, $sourcePaths);
			$requiredContent = $this->handleClassRequires($requiredContent, $sourcePaths);
			$content = $requiredContent."\n".$content;
		}
		return $content;
	}

	public function fetch($script, $sources)
	{
		$sourcePaths = explode(',', $sources);
		$sourcePaths []= "../../";
		$scriptContent = $this->loadJSScript($script,$sourcePaths);
		$scriptContent = $this->handleClassRequires($scriptContent,$sourcePaths);
		
		// http://code.google.com/p/minify/source/browse/#svn/trunk/min/lib
		if($this->minify == true)
			return JSMin::minify($scriptContent);
		else
			return $scriptContent;
	}
}
?>
